package com.haoshui.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haoshui.constants.ArticleConstans;
import com.haoshui.constants.RedisCacheConstans;
import com.haoshui.constants.SystemConstants;
import com.haoshui.domain.ResponseResult;
import com.haoshui.domain.dto.ArticleDto;
import com.haoshui.domain.entity.Article;
import com.haoshui.domain.entity.ArticleTag;
import com.haoshui.domain.vo.ArticleDetailVo;
import com.haoshui.domain.vo.ArticleListVo;
import com.haoshui.domain.vo.HotArticleVo;
import com.haoshui.domain.vo.PageVo;
import com.haoshui.mapper.ArticleMapper;
import com.haoshui.service.ArticleService;
import com.haoshui.service.ArticleTagService;
import com.haoshui.service.CategoryService;
import com.haoshui.utils.BeanCopyUitls;
import com.haoshui.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private CategoryService categoryService;

    @Override
    public ResponseResult<Article> hotArticleList() {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //不是草稿
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //查询最热的
        queryWrapper.orderByDesc(Article::getViewCount);
        //查询10个
        Page<Article> page = new Page<>(1,SystemConstants.HOT_ARTICLE_COUNTS);
        page(page,queryWrapper);

        List<Article> articles = page.getRecords();
        articles = articles.stream()
                .map(article -> article.setViewCount(findViewCount(article.getId())))
                .collect(Collectors.toList());
        return ResponseResult.okResult(BeanCopyUitls.copyBeanList(articles, HotArticleVo.class));
    }

    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId) {

        //查询正式发布的文章
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);

        //如果有categoryId， 只查找这一类的
        queryWrapper.eq(Objects.nonNull(categoryId) && categoryId>0, Article::getCategoryId, categoryId);

        //置顶的文章在前
        queryWrapper.orderByDesc(Article::getIsTop);

        //开始查找
        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page, queryWrapper);

        //查询categoryName
        List<Article> records = page.getRecords();


        //查询categoryName
        records.stream()
                .map(article -> article.setCategoryName(categoryService.getById(article.getCategoryId()).getName()))
                .collect(Collectors.toList());

//        for (Article record : records) {
//            Category category = categoryService.getById(record.getCategoryId());
//            record.setCategoryName(category.getName());
//        }


        //封装VO
        List<ArticleListVo> articleListVos = BeanCopyUitls.copyBeanList(page.getRecords(), ArticleListVo.class);


        PageVo pageVo = new PageVo( articleListVos, page.getTotal());

        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult getArticleDetail(Long id) {
        //查找文章
        Article article = getById(id);

        //在redis中查找viewCount
        article.setViewCount(findViewCount(id));

        //根据categoryId，查找categoryName
        article.setCategoryName(categoryService.getById(article.getCategoryId()).getName());

        //封装Vo
        ArticleDetailVo articleDetailVo = BeanCopyUitls.copyBean(article, ArticleDetailVo.class);

        return ResponseResult.okResult(articleDetailVo);
    }

    @Override
    public ResponseResult updateViewCount(Long id) {
        redisCache.increamentMapValue(RedisCacheConstans.VIEW_COUNT_KEY_IN_REDIS, id.toString(), 1);
        return ResponseResult.okResult();
    }

    @Autowired
    private ArticleTagService articleTagService;

    @Override
    public Long addArticle(ArticleDto articleDto) {
        Article article = BeanCopyUitls.copyBean(articleDto, Article.class);
        //博文保存到article
        boolean save = save(article);

        List<ArticleTag> collect = articleDto.getTags().stream()
                .map(tag -> new ArticleTag(article.getId(), tag))
                .collect(Collectors.toList());


        collect.stream().forEach(new Consumer<ArticleTag>() {
            @Override
            public void accept(ArticleTag articleTag) {
                articleTagService.save(articleTag);
            }
        });

        //TOdo 如果标签插入失败，就应该将文章也删除掉，两者插入应该是同步的


        if(save){
            return  article.getId();
        }else{
            //TODO 抛出异常或者返回信息
            return -1L;
        }
    }

    @Override
    public Long addArticle2(ArticleDto articleDto) {
        Article article = BeanCopyUitls.copyBean(articleDto, Article.class);
        //博文保存到article
        boolean save = save(article);

        List<ArticleTag> collect = articleDto.getTags().stream()
                .map(tag -> new ArticleTag(article.getId(), tag))
                .collect(Collectors.toList());


        collect.stream().forEach(new Consumer<ArticleTag>() {
            @Override
            public void accept(ArticleTag articleTag) {
                articleTagService.save(articleTag);
            }
        });

        //TOdo 如果标签插入失败，就应该将文章也删除掉，两者插入应该是同步的


        if(save){
            return  article.getId();
        }else{
            //TODO 抛出异常或者返回信息
            return -1L;
        }
    }

    @Override
    public Page<Article> findArticle(Integer pageNum, Integer pageSize, String title, String summary) {
        //设置查询条件
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //没有被逻辑删除
        queryWrapper.eq(Article::getDelFlag, ArticleConstans.ARTICLE_EXIST);
        //如果有title，模糊查询title
        queryWrapper.like(Objects.nonNull(title) && StringUtils.hasText(title), Article::getTitle, title );
        //如果存在summary, 模糊查询summary
        queryWrapper.like(Objects.nonNull(summary) && StringUtils.hasText(summary), Article::getSummary, summary );

        //页查询
        Page page = new Page(pageNum, pageSize);
        Page<Article> articlePage = page(page, queryWrapper);

        //返回结果
        return  articlePage;
    }

    @Override
    public Article getArticle(Long id) {
        //查询article
        Article article = getById(id);

        return article;
    }

    @Override
    public boolean updateArticle(Article article) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getId, article.getId());
        boolean update = update(article, queryWrapper);

        return update;
    }

    @Override
    public void updateViewCountToDateBase(List<Article> articles) {
        for (Article article : articles) {
            Article byId = getById(article.getId());
            if(byId == null){
                continue;
            }
            getBaseMapper().updateViewCount(article.getId(), article.getViewCount());
        }
    }


    /**
     * 在redis中查找指定id的viewcount
     * @param id
     * @return
     */
    private Long findViewCount(Long id){
        //在redis中查找viewCount
        Integer viewCount = redisCache.getCacheMapValue(RedisCacheConstans.VIEW_COUNT_KEY_IN_REDIS, id.toString());
        return viewCount.longValue();
    }
}
